import { defineStore } from 'pinia';
import { loginApi, getUserInfo, doLogout } from '/@/api/user.ts';
import { TOKEN_KEY, USER_INFO_KEY } from '/@/enum/cacheEnum.ts';
import { getBaseLogin, PageEnum } from '/@/enum/pageEnum.ts';
import { getAuthCache, setAuthCache } from '/@/utils/auth.ts';
import { useRouter } from 'vue-router';
import { LoginInfo, LoginParams, UserInfo } from '/@/store/modules/storeType.ts';
import { store } from '/@/store';
import { message } from 'ant-design-vue';

const router = useRouter();
export const useUserStore = defineStore({
    id: 'app-user',
    state: () => ({
        token: '',
        userInfo: null,
        //登录返回信息
        loginInfo: null,
        themeType: '', // dark 1, light 2
        flag1: '', //银川权限标识
        flag2: '', //西安权限标识
        flag3: '', //新版大屏标识
        centerId: '', //中心点id
        centerInfo: null, //应急中心信息
    }),
    getters: {
        getUserInfo(): UserInfo {
            return (this.userInfo && Object.keys(this.userInfo).length > 0) || getAuthCache(USER_INFO_KEY) || {};
        },
        getLoginInfo(): LoginInfo {
            return this.loginInfo || {};
        },
        getToken(): string {
            return this.token || getAuthCache(TOKEN_KEY);
        },
        getThemeType(): string {
            return this.themeType || getAuthCache('themeType');
        },
        getFlag1(): string {
            return this.flag1 || getAuthCache('flag1');
        },
        getFlag2(): string {
            return this.flag2 || getAuthCache('flag2');
        },
        getFlag3(): string {
            return this.flag3 || getAuthCache('flag3');
        },
        getCenterId(): string {
            return this.centerId || getAuthCache('centerId');
        },
        getCenterInfo(): any {
            return this.centerInfo || getAuthCache('centerInfo');
        },
    },
    actions: {
        setToken(info: string | undefined) {
            this.token = info ? info : '';
            setAuthCache(TOKEN_KEY, info);
        },
        setUserInfo(info: UserInfo | null) {
            this.userInfo = info;
            setAuthCache(USER_INFO_KEY, info);
        },
        setLoginInfo(info: LoginInfo | null) {
            this.loginInfo = info;
        },
        setThemeType(info: string | undefined) {
            this.themeType = info ? info : '';
            setAuthCache('themeType', info);
        },
        setFlag1(info: string | undefined) {
            this.flag1 = info ? info : '';
            setAuthCache('flag1', info);
        },
        setFlag2(info: string | undefined) {
            this.flag2 = info ? info : '';
            setAuthCache('flag2', info);
        },
        setFlag3(info: string | undefined) {
            this.flag3 = info ? info : '';
            setAuthCache('flag3', info);
        },
        setCenterId(info: string | undefined) {
            this.centerId = info ? info : '';
            setAuthCache('centerId', info);
        },
        setCenterInfo(info: any) {
            this.centerInfo = info;
            setAuthCache('centerInfo', info);
        },
        /**
         * 登录事件
         */
        async login(params: LoginParams) {
            try {
                const { goHome = true, mode, ...loginParams } = params;
                const data = await loginApi(loginParams, mode);
                if (data && data['result']) {
                    const { token, userInfo } = data.result;
                    // save token
                    this.setToken(token, false);
                    this.setUserInfo(userInfo);
                    return { userInfo, token };
                } else {
                    return Promise.reject(data);
                }
            } catch (error) {
                return Promise.reject(error);
            }
        },
        /**
         * 登录完成处理
         * @param goHome
         */
        async afterLoginAction(goHome?: boolean, data?: any): Promise<any | null> {
            if (!this.getToken) return null;
            //获取用户信息
            const userInfo = await this.getUserInfoAction();
            const { multi_depart, departs } = data;
            await this.setLoginInfo({ multi_depart, departs, isLogin: true });
            return data;
        },
        /**
         * @desc 获取用户信息
         */
        async getUserInfoAction() {
            if (!this.getToken) {
                return null;
            }
            // @ts-ignore
            const { userInfo } = await getUserInfo();
            if (userInfo) {
                this.setUserInfo(userInfo);
            }
            return userInfo;
        },
        /**
         * @desc 退出登录
         */
        async logout(goLogin = false) {
            if (this.getToken) {
                try {
                    await doLogout();
                } catch {
                    console.log('注销Token失败');
                }
            }
            this.setToken('');
            this.setUserInfo(null);
            this.setLoginInfo(null);
            console.log('goLogin', goLogin);
            let path = getBaseLogin();
            goLogin && router.replace({ path: path });
        },
    },
});

export function useUserStoreWithOut() {
    return useUserStore(store);
}
